package fun.flyee.android.pengshan.models;

import android.text.TextUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.maps.model.LatLng;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import fun.flyee.android.pengshan.Storage;
import fun.flyee.android.pengshan.api.ApiClient;
import fun.flyee.android.pengshan.utils.GeoUtil;
import fun.flyee.android.pengshan.utils.Logger;

public class GeoRail {

    List<LatLng> rail;

    public static void loadRail(Callback callback) {
        String str = Storage.get("rail_points");
        if (!TextUtils.isEmpty(str)) {
            GeoRail geoRail = new GeoRail();
            geoRail.setRail(str);
            callback.onLoaded(geoRail);
        } else {
            ApiClient.get("/back-stage/trajectory/mineRail", new JSONObject(), (result) -> {
                if (result.code == 200) {
                    JSONObject json = (JSONObject) result.data;
                    String points = json.getString("coordinatesStreet");
                    if (!TextUtils.isEmpty(points)) {
                        Storage.set("rail_points", points);
                        GeoRail geoRail = new GeoRail();
                        try {
                            geoRail.setRail(points);
                            callback.onLoaded(geoRail);
                        } catch (Exception e) {
                            Logger.e("runtime", e);
                            callback.onLoaded(null);
                        }
                        return;
                    }
                }
                callback.onLoaded(null);
            });
        }
    }

    private void setRail(String str) throws RuntimeException {
        JSONArray array = JSONArray.parseArray(str);
        if (array == null) {
            throw new RuntimeException("rail is null");
        }
        Iterator it = array.iterator();
        rail = new ArrayList<>();
        while (it.hasNext()) {
            JSONArray tuple = (JSONArray) it.next();
            Double lat = Double.parseDouble(tuple.get(1).toString());
            Double lng = Double.parseDouble(tuple.get(0).toString());
            LatLng point = new LatLng(lat, lng);
            rail.add(point);
        }
    }

    public boolean inRail(double lat, double lng) {
        LatLng point = new LatLng(lat, lng);

        return GeoUtil.isPolygonContainsPoint(rail, point);
    }

    public interface Callback {
        void onLoaded(GeoRail rail);
    }
}
